
<style scoped>
.handle-box {
    margin: 0 0 20px;
}
</style>
<!-- tsx -->
<template>
    <div class="package">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-tickets"></i> 每月商品销售统计 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-select placeholder="发放类型" style="width: 200px; margin: 0 20px 0 0" clearable v-model="query.categoryID">
                    <el-option v-for="(item, index) in grantList" :key="index" :label="item.name" :value="item.categoryID"></el-option>
                </el-select>
                <el-select placeholder="卡片服务类别" style="width: 200px; margin: 0 20px 0 0" clearable v-model="query.category">
                    <el-option v-for="(item, index) in dictList" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-input placeholder="推荐人账号" v-model="query.parentMobile" style="width: 200px; margin: 0 20px 0 0"></el-input>
                <el-button type="primary" @click="getList" size="small" style="margin: 0 0 0 20px">搜索</el-button>
                <el-button type="primary" @click="showadd = true" size="small" style="margin: 0 0 0 20px">批量发卡</el-button>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                <!-- <el-table-column prop="id" width="250" label="ID" align="center"></el-table-column> -->
                <el-table-column prop="categoryName" label="基础类型名称" align="center"></el-table-column>
                <el-table-column prop="parentMobile" label="推荐账号" align="center"></el-table-column>
                <el-table-column prop="category" label="发放类型" align="center"></el-table-column>
                <el-table-column prop="name" label="单位/个人名称" align="center"></el-table-column>
                <el-table-column prop="count" label="发放数量" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template slot-scope="scope">
                        <span style="color: #00bc00" v-if="scope.row.status == '启用'">{{ scope.row.status }}</span>
                        <span style="color: #f56c6c" v-else>{{ scope.row.status }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createdOn" label="创建时间" align="center"></el-table-column>
                <el-table-column label="操作" width="150" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger" v-if="scope.row.status == '启用'" @click="close(scope.row.id)">禁用</el-button>
                        <el-button size="mini" type="success" v-else @click="open(scope.row.id)">启用</el-button>
                        <el-button size="mini" type="warning" @click="exportData(scope.row.id)">导出</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="sizeChange"
                    @current-change="pageChange"
                    :current-page="query.pageIndex"
                    :page-sizes="[20, 50, 100, 200]"
                    :page-size="query.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                >
                </el-pagination>
            </div>
        </div>

        <el-dialog title="新增" :visible.sync="showadd" width="500px">
            <el-form ref="send" :model="addFrom" label-width="150px">
                <el-form-item label="卡片服务类别:">
                    <el-select placeholder="卡片服务类别" style="width: 200px; margin: 0 20px 0 0" clearable v-model="addFrom.categoryID">
                        <el-option v-for="(item, index) in dictList" :key="index" :label="item.name" :value="item.categoryID"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="推荐人:">
                    <el-input v-model="addFrom.mobile" style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="发放类型:">
                    <el-select placeholder="发放类型" style="width: 200px; margin: 0 20px 0 0" clearable v-model="addFrom.category">
                        <el-option v-for="(item, index) in grantList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="卡片级别:">
                    <el-select placeholder="卡片级别" style="width: 200px;" clearable v-model="addFrom.defaultRank">
                        <el-option v-for="(item,index) in rankList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="单位/个人 名称:">
                    <el-input v-model="addFrom.name" style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="发放数量:">
                    <el-input v-model="addFrom.count" style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="状态:">
                    <el-radio v-model="addFrom.status" :label="true">启用</el-radio>
                    <el-radio v-model="addFrom.status" :label="false">禁用</el-radio>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showadd = false">取 消</el-button>
                <el-button type="primary" @click="addOne" :loading="sureData">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script >
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import { PagingGrant, GrantTypeDict, CategoryDict, BatchCardGrant, DisableGrant, EnableGrant, Export } from '@/api/card';
import XLSX from 'xlsx';
export default {
    // import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        // 这里存放数据
        return {
            query: {
                pageIndex: 1,
                pageSize: 20,
                categoryID: '',
                parentMobile: '',
                category: ''
            },
            outFile:'',
            showDetail: false,
            tableDetail: [],
            tableData: [],
            pageTotal: 0,
            grantList: [],
            dictList: [],
            showadd: false,
            addFrom: {
                status: true,
                categoryID: ''
            },
            sureData:false
        };
    },
    // 过滤器
    filters: {},
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {},
    // 方法集合
    methods: {
        pageChange(e) {
            this.query.pageIndex = e;
            this.getList();
        },
        getList() {
            PagingGrant(this.query).then((res) => {
                this.tableData = res.Data.list;
                this.pageTotal = res.Data.paging.totalItemCount;
            });
        },
        sizeChange(e) {
            this.query.pageSize = e;
            this.getList();
        },
        close(id) {
            DisableGrant({ id: id }).then((res) => {
                if (res.RequestStatus == 200) {
                    this.$message.success('禁用成功');
                    this.getList();
                }
                // console.log(res)
            });
        },
        open(id) {
            EnableGrant({ id: id }).then((res) => {
                if (res.RequestStatus == 200) {
                    this.$message.success('启用成功');
                    this.getList();
                }
                console.log(res);
            });
        },
        addOne() {
            console.log(this.addFrom, this.dictList);
            this.sureData = true
            const loading = this.$loading({
            lock: true,
            text: '正在生成',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
            });
            BatchCardGrant(this.addFrom).then((res) => {
                if (res.RequestStatus == 200) {
                    this.$message.success('添加成功');
                    this.getList();
            this.sureData = false
            loading.close();
                    this.showadd = false;
                    this.addFrom = {
                        status: true
                    };
                }
            });
        },
        downloadExl: function (json, downName, type) {
            // 导出到excel['推荐人', '推荐账号', '享优卡号', '享优卡卡密', '卡状态']
            // ['parentName', 'parentMobile', 'cardNo', 'privateKey', 'status']
            json.unshift({
                    parentName:'推荐人',
                    parentMobile:'推荐账号',
                    cardNo:'享优卡号',
                    privateKey:'享优卡卡密',
                    status:'卡状态',
                })
            let keyMap = []; // 获取键
            for (let k in json[0]) {
                keyMap.push(k);
            }
            console.info('keyMap', keyMap, json);
            let tmpdata = []; // 用来保存转换好的json
            json.map((v, i) =>
                keyMap.map((k, j) =>
                    Object.assign(
                        {},
                        {
                            v: v[k],
                            position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
                        }
                    )
                )
            )
                .reduce((prev, next) => prev.concat(next))
                .forEach(function (v) {
                    tmpdata[v.position] = {
                        v: v.v
                    };
                });
            let outputPos = Object.keys(tmpdata); // 设置区域,比如表格从A1到D10
            let tmpWB = {
                SheetNames: ['mySheet'], // 保存的表标题
                Sheets: {
                    mySheet: Object.assign(
                        {},
                        tmpdata, // 内容
                        {
                            '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
                        }
                    )
                }
            };
            let tmpDown = new Blob(
                [
                    this.s2ab(
                        XLSX.write(
                            tmpWB,
                            { bookType: type === undefined ? 'xlsx' : type, bookSST: false, type: 'binary' } // 这里的数据是用来定义导出的格式类型
                        )
                    )
                ],
                {
                    type: ''
                }
            ); // 创建二进制对象写入转换好的字节流
            var href = URL.createObjectURL(tmpDown); // 创建对象超链接
            let a = document.createElement('a')
            a.download ='发卡信息.xlsx'; // 下载名称
            a.href = href; // 绑定a标签
            a.click(); // 模拟点击实现下载
            setTimeout(function () {
                // 延时释放
                URL.revokeObjectURL(tmpDown); // 用URL.revokeObjectURL()来释放这个object URL
            }, 100);
        },
        s2ab: function (s) { // 字符串转字符流
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
        formatJson(filterVal, jsonData) {
            return jsonData.map((v) => filterVal.map((j) => v[j]));
        },
        exportData(id) {
            Export({ id: id }).then((res) => {
                // console.log(res);
                this.downloadExl(res.Data.cardList,'发卡信息')
                return false
                if (res.Data.cardList.length == 0) {
                    this.$message.error('没有卡信息，不能导出');
                    return false;
                }
                require.ensure([], () => {
                    const { export_json_to_excel } = require('../../utils/Export2Excel.js');
                    const tHeader = ['推荐人', '推荐账号', '享优卡号', '享优卡卡密', '卡状态'];
                    const filterVal = ['parentName', 'parentMobile', 'cardNo', 'privateKey', 'status'];
                    const list = res.Data.cardList;
                    // console.log(res)
                    const data = this.formatJson(filterVal, list);
                    export_json_to_excel(tHeader, data, '发卡信息');
                });
            });
        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
        // console.log(123);
        this.getList();
        GrantTypeDict().then((res) => {
            this.grantList = res.Data.dropList;
        });
        CategoryDict().then((res) => {
            this.dictList = res.Data.dropList;
        });
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, // 生命周期 - 创建之前
    beforeMount() {}, // 生命周期 - 挂载之前
    beforeUpdate() {}, // 生命周期 - 更新之前
    updated() {}, // 生命周期 - 更新之后
    beforeDestroy() {}, // 生命周期 - 销毁之前
    destroyed() {}, // 生命周期 - 销毁完成
    ctivated() {} // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>